package slxy.jiangtao.dts.controller.business;

import com.alibaba.fastjson.JSON;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import slxy.jiangtao.dts.controller.BaseController;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.bean.FormCriteria;
import slxy.jiangtao.dts.core.common.bean.FormQuery;
import slxy.jiangtao.dts.core.common.bean.JSONResult;
import slxy.jiangtao.dts.core.common.hibernate.qbc.Page;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.DateUtils;
import slxy.jiangtao.dts.entity.business.Task;
import slxy.jiangtao.dts.entity.business.UserTaskDone;
import slxy.jiangtao.dts.entity.sys.Depart;
import slxy.jiangtao.dts.entity.sys.DictionariesTask;
import slxy.jiangtao.dts.entity.sys.User;
import slxy.jiangtao.dts.service.sys.TaskService;
import slxy.jiangtao.dts.service.sys.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/4/17.
 * 说明：任务controller
 */
@Controller
@RequestMapping("task")
public class TaskController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);
    @Autowired
    private TaskService taskService;
    @Autowired
    private UserService userService;

    @RequestMapping("index")
    public String index(ModelMap modelMap) {
        FormQuery formQuery = new FormQuery("business.Task");
        ArrayList<FormCriteria> formCriterias = new ArrayList<>();
        //默认只显示本月创建的任务
        formCriterias.add(new FormCriteria("creatTime", "like", DateUtils.getDate("yyyy-MM") + "%"));
        Page page = commonService.getPage(formQuery);
        modelMap.addAttribute("page", JSON.toJSONString(page));
        return "task/index";
    }

    /**
     * 添加或更新页面跳转
     */
    @RequestMapping("page/{addOrUpdate}")
    public String addPage(ModelMap modelMap, @PathVariable String addOrUpdate, HttpServletRequest request) {
        Integer id = null;
        if (addOrUpdate.trim().equals("update")) {//判断是否为更新页面跳转
            id = Integer.parseInt(request.getParameter("id"));
            Task task = commonService.get(Task.class, id);
            modelMap.put("sysFiles", getFiles(task.getFiles()));
            modelMap.put("task", task);
        }

        //获取所有负责人
        List<User> managers = userService.getManagers();
        managers.sort(Comparator.comparing(User::getRoleId));//按角色排序
        modelMap.put("managers", JSON.toJSONString(managers));

        //获取任务类型集合
        List<DictionariesTask> dictionariesTaskList = commonService.getList(DictionariesTask.class);
        modelMap.put("dictionariesTaskList", JSON.toJSONString(dictionariesTaskList));

        return "task/" + addOrUpdate;
    }


    /**
     * 修改或添加任务提交
     */
    @RequestMapping(value = "submit/{action}", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult addSubmint(Task task, Integer[] charges, @PathVariable String action, HttpServletRequest request) {
        String organizationtor = "";
        if (charges != null) {
            for (Integer charge : charges) {
                organizationtor = organizationtor + "," + charge;
            }
        }
        task.setOrganizationtor(organizationtor);
        try {
            if(action.trim().equals("add") ||action.trim().equals("update")){
                if (action.trim().equals("add")) {
                    taskService.add(task, getUserInSession(request));
                } else {
                    commonService.updateEntity(task);
                }
            }else {
                return JSONResult.failure("无效路径");
            }
        } catch (Exception e) {
            logger.error("任务创建失败", e);
            return JSONResult.failure("操作失败");
        }
        return JSONResult.success();
    }


    /**
     * 完成任务状态改变
     */
    @RequestMapping("complete/{id}")
    @ResponseBody
    public JSONResult complete(@PathVariable Integer id) {
        Task task = commonService.get(Task.class, id);
        task.setState(Constants.TASK_ED);
        commonService.updateEntity(task);
        return JSONResult.success();
    }

    /**
     * 完成任务参与者添加
     */
    @RequestMapping("join/{id}")
    @ResponseBody
    public JSONResult join(@PathVariable Integer id, HttpServletRequest request) {
        try {
            Task task = commonService.get(Task.class, id);
            User userInSession = getUserInSession(request);

            //判断该用户已经做过该任务的此操作
            DetachedCriteria dc1 = DetachedCriteria.forClass(UserTaskDone.class);
            dc1.add(Restrictions.eq("userId", userInSession.getId()))
                    .add(Restrictions.eq("taskId", id));
            if (commonService.findByDetached(dc1).size() > 0) {//参与情况
                return JSONResult.success("此操作已做过不需再进行");
            }

            UserTaskDone userTaskDone = new UserTaskDone();
            userTaskDone.setUserId(userInSession.getId());
            userTaskDone.setTaskId(id);
            userTaskDone.setExecuteTime(task.getExecuteTime());
            commonService.save(userTaskDone);
        } catch (Exception e) {
            logger.error("参与失败", e);
            return JSONResult.failure("参与失败");
        }
        return JSONResult.success();
    }

    @RequestMapping("delete/{id}")
    @ResponseBody
    public JSONResult delete(@PathVariable Integer id, HttpServletRequest request) {
        try {
            taskService.delete(id);
            logger.info(getUserInSession(request).getName() + "--删除一个任务");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return JSONResult.failure("删除失败,请联系管理员");
        }
        return JSONResult.success();
    }

    /**
     * 详情页面跳转
     */
    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id, ModelMap modelMap) {
        Task task = commonService.get(Task.class, id);
        if (task.getState().equals(Constants.TASK_ED)) {//获取完成用户的姓名集合
            List<String> doneUsers = taskService.getDoneUser(id);
            modelMap.put("doneUsers", doneUsers);
        }
        modelMap.put("sysFiles", getFiles(task.getFiles()));
        //负责干部
        modelMap.put("managers", task.getOrganizationtor().equals("") ? "" : taskService.getManagersById(task.getOrganizationtor().substring(1)));
        modelMap.put("type", commonService.get(DictionariesTask.class, task.getType()).getName());
        modelMap.put("task", task);
        return "task/detail";
    }

    /**
     * 考勤分析首页
     */
    @RequestMapping("analysis/index")
    public String analysisIndex(HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("departName", JSON.toJSONString(commonService.get(Depart.class, getUserInSession(request).getDepartId()).getName()));
        modelMap.put("datas", JSON.toJSONString(taskService.getInfo(getUserInSession(request).getDepartId(), DateUtils.getDate("yyyy-MM"))));
        modelMap.put("departList", JSON.toJSON(commonService.getList(Depart.class)));
        return "task/analysis/index";
    }

    /**
     * 获取考勤分析的数据
     */
    @RequestMapping(value = "analysis/data", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult getData(@RequestParam Integer departId, @RequestParam String time) {
        return JSONResult.success(JSON.toJSON(taskService.getInfo(departId, time)));
    }

    @RequestMapping(value = "analysis/personalDetail")
    public String personalDetail(@RequestParam String username, @RequestParam String time, ModelMap modelMap) {
        List<List<String>> data = taskService.getPersonalTasks(username, time);
        modelMap.put("data", data);
        return "task/analysis/personalDetail";
    }

}
